package timing.ukulele.item.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import timing.ukulele.item.mapper.ItemMapper;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.common.flow.FlowData;
import timing.ukulele.common.form.FormTemplateData;
import timing.ukulele.common.item.ItemData;
import timing.ukulele.common.portal.SystemData;
import timing.ukulele.item.client.FlowClient;
import timing.ukulele.item.client.FormClient;
import timing.ukulele.item.client.SystemClient;
import timing.ukulele.item.persistent.Item;
import timing.ukulele.persistent.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ItemService extends BaseService<ItemMapper, Item> {

    @Resource
    private SystemClient systemClient;
    @Resource
    private FormClient formClient;
    @Resource
    private FlowClient flowClient;


    /**
     * 获取分页
     *
     * @param name    查询名称
     * @param current 当前也页，从1开始
     * @param size    每页大小
     * @return 模板数据
     */
    public IPage<Item> getPage(String name, String system, int current, int size, HashMap<String, Object> map) {
        Page<Item> page = new Page<>(current, size);
        LambdaQueryWrapper<Item> qw = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            qw.like(Item::getName, name);
        }
        List<Long> systemIds = null;
        if (!"".equals(system)) {
            String[] split = system.split(",");
            if (!"0".equals(split[0])) {
                systemIds = Arrays.asList(split).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                qw.in(Item::getSystemId, systemIds);
            }
        }
        qw.orderByDesc(Item::getId);
        IPage<Item> iPage = getBaseMapper().selectPage(page, qw);
        List<Item> items = iPage.getRecords();
        Map<Long, String> systemMap = null;
        final ResponseResult<List<SystemData>> allSystem = systemClient.all();
        if (allSystem != null && !CollectionUtils.isEmpty(allSystem.getData())) {
            systemMap = allSystem.getData().stream().collect(Collectors.toMap(SystemData::getId, SystemData::getName));
        }
        for (Item item : items) {
            if (item.getTemplateId() != null && item.getTemplateId() > 0) {
                FormTemplateData formTemplate = null;
                final ResponseResult<FormTemplateData> result = formClient.findById(item.getTemplateId());
                if (result != null)
                    formTemplate = result.getData();
                if (formTemplate != null) {
                    item.setTemplateName(formTemplate.getName());
                }
            }
            if (item.getFlowId() != null && item.getFlowId() > 0) {
                FlowData flowData = null;
                final ResponseResult<FlowData> result = flowClient.findById(item.getFlowId());
                if (result != null)
                    flowData = result.getData();
                if (flowData != null)
                    item.setFlowName(flowData.getName());
            }
            if (!CollectionUtils.isEmpty(systemMap))
                item.setSystemName(systemMap.get(item.getSystemId()));
        }
        return iPage;
    }

    public Item getByCode(String code) {
        Item item = new Item();
        item.setCode(code);
        return getBaseMapper().selectOne(new QueryWrapper<>(item));
    }

    public List<ItemData> getBySystemId(Long systemId) {
        Map<String, Object> params = new HashMap<>();
        params.put("system_id", systemId);
        List<Item> items = getBaseMapper().selectByMap(params);
        List<ItemData> itemDatas = new ArrayList<>();
        if (!CollectionUtils.isEmpty(items)) {
            for (Item item : items) {
                ItemData itemData = new ItemData();
                BeanUtils.copyProperties(item, itemData);
                itemDatas.add(itemData);
            }
        }
        return itemDatas;
    }

    public int saveItem(Item item) {
        ResponseResult<SystemData> system = systemClient.getById(item.getSystemId());
        LambdaQueryWrapper<Item> lqw = new LambdaQueryWrapper<>();
        lqw.likeRight(Item::getCode, system.getData().getCode() + "_");
        long count = getBaseMapper().selectCount(lqw);
        StringBuilder code = new StringBuilder();
        code.append(system.getData().getCode()).append("_").append(String.format("%05d", count + 1));
        item.setCode(code.toString());
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        return getBaseMapper().insert(item);
    }

}
